/**
 * @Description: 封装动画
 * @author bev
 * @date 2019/10/16
 * @time 11:54
 */

export default class FLIP {
  constructor(firstElement, lastElement, component) {
    this.firstElement = firstElement;
    this.lastElement = lastElement;
    this.component = component;
  }

  async init() {
    const { firstElement, lastElement, component } = this;
    // 获取节点 top left
    const startPosition = await this.getBoundingClientRect(
      firstElement,
      component
    );
    const endPosition = await this.getBoundingClientRect(
      lastElement,
      component
    );

    // 算位移
    return {
      dx: startPosition.left - endPosition.left + 7,
      dy: startPosition.top - endPosition.top + 7
    };
  }

  async animation() {
    const { dx, dy } = await this.init();
    const animation = uni.createAnimation({
      transformOrigin: "top left",
      duration: 600,
      timingFunction: "ease-in",
      delay: 1300
    });

    animation
      .translate(dx, dy)
      .scale(0.2)
      .step();

    return animation.export();
  }

  async animationScale() {
    const { dx, dy } = await this.init();
    const animation = uni.createAnimation({
      transformOrigin: "top left",
      duration: 300,
      timingFunction: "ease-in",
      delay: 0
    });

    animation
      .translate(dx - 20, dy - 20)
      .scale(1)
      .step();

    return animation.export();
  }

  async animationEnd() {
    const animation = uni.createAnimation({});

    animation
      .translate(0, 0)
      .scale(1)
      .step();
    return animation.export();
  }

  querySelector(el, component) {
    return uni
      .createSelectorQuery()
      .in(component)
      .select(el);
  }

  getBoundingClientRect(el, component) {
    return new Promise((resolve, reject) => {
      this.querySelector(el, component)
        .boundingClientRect(e => {
          const { top, left, width, height } = e;
          resolve({ top, left, width, height });
        })
        .exec();
    });
  }
}
